import smtplib
from email.mime.text import MIMEText
from email.utils import formataddr
from email.mime.multipart import MIMEMultipart
import os
import MyConfigParser

my_sender='xxx@qq.com'      # 发件人邮箱账号
my_pass = '1234'     # 发件人邮箱密码
my_user='xxx@qq.com'      # 收件人邮箱账号，我这边发送给自己

#加载配置文件读取账户密码
def loadConfig():
    global my_sender
    global my_pass
    global my_user
    conf = MyConfigParser.MyConfigParser()
    conf.read('config.ini',"utf-8")
    my_sender = conf.get("email", "sender")
    my_pass = conf.get("email", "pass")
    my_user = conf.get("email", "addressee")

#发送邮件 参数是文件绝对路径
def mail(files = []):
    loadConfig()
    ret=True
    try:
        #创建一个带附件的实例
        message = MIMEMultipart()
        message['From'] = formataddr(["FromPy",my_sender])
        message['To'] =  formataddr(["TOSelf",my_user])
        subject = 'SMTP_文件'
        message['Subject'] = subject
        #邮件正文内容
        message.attach(MIMEText('wechat to email', 'plain', 'utf-8'))
        for file in files:
            # 构造附件1，传送当前目录下的 test.txt 文件
            att1 = MIMEText(open(file, 'rb').read(), 'base64', 'utf-8')
            att1["Content-Type"] = 'application/octet-stream'
            filename = os.path.basename(file)
            att1.add_header("Content-Disposition", "attachment", filename=("utf-8", "", filename))
            print(att1["Content-Disposition"])
            # 附件名称非中文时的写法
            # att["Content-Disposition"] = 'attachment; filename="test.html")'
            message.attach(att1)
        server=smtplib.SMTP_SSL("smtp.qq.com", 465)  # 发件人邮箱中的SMTP服务器，端口是25
        server.login(my_sender, my_pass)  # 括号中对应的是发件人邮箱账号、邮箱密码
        server.sendmail(my_sender,[my_user,],message.as_string())  # 括号中对应的是发件人邮箱账号、收件人邮箱账号、发送邮件
        server.quit()  # 关闭连接
    except Exception as e:  # 如果 try 中的语句没有执行，则会执行下面的 ret=False
        print(e)
        ret=False
    return ret


if __name__ == "__main__":
    file_list = []
    ret=mail(file_list)
    if ret:
        print("邮件发送成功")
    else:
        print("邮件发送失败")